package com.tpvlog.im.sdk.android;

import com.tpvlog.im.common.Constants;
import com.tpvlog.im.common.Message;
import com.tpvlog.im.common.Request;
import com.tpvlog.im.common.Response;
import com.tpvlog.im.protocal.AuthenticateResponseProto;
import com.tpvlog.im.protocal.MessagePushRequestProto;
import com.tpvlog.im.protocal.MessagePushResponseProto;
import com.tpvlog.im.protocal.MessageSendResponseProto;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class ImClientHandler extends ChannelInboundHandlerAdapter {

    private ImClient imClient;

    public ImClientHandler(ImClient imClient) {
        this.imClient = imClient;
    }

    /**
     * 与目标主机建立连接
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buffer = (ByteBuf) msg;
        Message message = new Message(buffer);
        System.out.println("收到IM-GATEWAY发送过来的消息，消息类型为：" + message.getMessageType());

        // 1.响应消息（客户端SDK主动发送，IM-GATEWAY响应）
        if (message.getMessageType() == Constants.MESSAGE_TYPE_RESPONSE) {
            Response response = message.toResponse();
            // 认证
            if (response.getRequestType() == Constants.REQUEST_TYPE_AUTHENTICATE) {
                AuthenticateResponseProto.AuthenticateResponse authenticateResponse =
                        AuthenticateResponseProto.AuthenticateResponse.parseFrom(response.getBody());
                System.out.println("认证请求收到响应：" + authenticateResponse);
                imClient.setAuthConnected(true);
            }
            // 单聊
            else if (response.getRequestType() == Constants.REQUEST_TYPE_SEND_MESSAGE) {
                MessageSendResponseProto.MessageSendResponse messageSendResponse =
                        MessageSendResponseProto.MessageSendResponse.parseFrom(response.getBody());
                System.out.println("客户端收到单聊消息的响应，messageId=" + messageSendResponse.getMessageId());
            }
        }
        // 2.请求消息（IM-GATEWAY主动发送，客户端SDK响应）
        else if (message.getMessageType() == Constants.MESSAGE_TYPE_REQUEST) {
            Request request = message.toRequest();
            // 消息推送
            if (request.getRequestType() == Constants.REQUEST_TYPE_PUSH_MESSAGE) {
                MessagePushRequestProto.MessagePushRequest messagePushRequest =
                        MessagePushRequestProto.MessagePushRequest.parseFrom(request.getBody());
                System.out.println("接收到一条消息推送：" + messagePushRequest);

                // 生成响应
                MessagePushResponseProto.MessagePushResponse.Builder builder =
                        MessagePushResponseProto.MessagePushResponse.newBuilder();
                builder.setMessageId(messagePushRequest.getMessageId());
                MessagePushResponseProto.MessagePushResponse messagePushResponse = builder.build();

                Response response = new Response(request, messagePushResponse.toByteArray());
                ctx.writeAndFlush(response.getBuffer());
                System.out.println("返回消息推送的响应给接入系统：" + messagePushResponse);
            }
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
